class Circle {
    /**
     * 原点对象构造函数
     * @param x  x坐标
     * @param y  y坐标
     * @param r  半径
     * @param _mx  移动的水平距离
     * @param _my  移动的垂直距离
     */
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.r = 3;
        this._mx = Math.random();
        this._my = Math.random();
    }

    /**
     * 画圆点
     * @param ctx canvas2d画笔上下文
     */
    drawCircle(ctx) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 360);
        ctx.closePath();
        ctx.fillStyle = 'rgba(204,204,204,0.30)';
        ctx.fill();
    }

    /**
     * 圆与圆之间的连线
     * 如果圆之间的距离大于d则不连线
     * @param ctx
     * @param _circle
     */
    drawLine(ctx, _circle) {
        let dx = this.x - _circle.x;
        let dy = this.y - _circle.y;
        let d = Math.sqrt(dx * dx + dy * dy);
        if (d < 100) {
            ctx.beginPath();
            ctx.moveTo(this.x, this.y);
            ctx.lineTo(_circle.x, _circle.y);
            ctx.strokeStyle = 'rgba(204,204,204,0.8)';
            ctx.stroke();
        }
    }

    move(w, h) {
        this._mx = (this.x < w && this.x > 0) ? this._mx : (-this._mx);
        this._my = (this.y < h && this.y > 0) ? this._my : (-this._my);
        this.x += this._mx / 2;
        this.y += this._my / 2;
    }
}

class currentCircle extends Circle {
    constructor(x, y) {
        super(x, y);
    }

    drawCircle(ctx) {
        ctx.beginPath();
        this.r = 8;
        ctx.arc(this.x, this.y, this.r, 0, 360);
        ctx.closePath();
        ctx.fillStyle = 'rgba(255, 77, 54, 0.6)';
        ctx.fill();
    }
}

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let ctx = canvas.getContext('2d');
let w = canvas.width = canvas.offsetWidth;
let h = canvas.height = canvas.offsetHeight;
let circles = [];
let deltaTime = 0;
let draw = function () {
    deltaTime = ++deltaTime % 3;
    if (deltaTime == 2) {
        ctx.clearRect(0, 0, w, h);
        for (let i = 0; i < circles.length; i++) {
            circles[i].move(w, h);
            circles[i].drawCircle(ctx);
            for (j = i + 1; j < circles.length; j++) {
                circles[i].drawLine(ctx, circles[j])
            }
        }
    }
    requestAnimationFrame(draw)
}

let init = function (num) {
    for (var i = 0; i < num; i++) {
        circles.push(new Circle(Math.random() * w, Math.random() * h));
    }
    draw();
}
window.addEventListener('load', init(100));

